#!/usr/bin/env python
# coding:utf-8

import requests
import sys
import json
import logging
import time, datetime
import os
import subprocess

time_sec=time.time()
day=time.strftime("%Y-%m-%d", time.localtime(time_sec))

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    filename=("/usr/local/zabbix/bin/phonelogs/phone-%s.log") % day,
                    filemode='a+')
console = logging.StreamHandler()
console.setLevel(logging.INFO)
logging.getLogger('').addHandler(console)
logger = logging.getLogger('phone')

phone_server = 'http://xxx.xx.xxx/v1/project/xxxx'
mobiles = sys.argv[1]
message = '{0}{1}'.format(sys.argv[2], sys.argv[3])

base_dir = os.path.dirname(os.path.realpath(__file__))
print base_dir
token_path = '%s/auth_token' % base_dir

def send_phone():
    content = pickup_data(message)
    if content is None:
        content = message
    header = {
        'Content-Type': "application/json",
    }
    logger.info('data')
    data = {
        "tenantCode":"YYJK",
        "proId":809,
        "phone":[
            {"num":mobiles,
            "param":content
            }
                ]
        }
    logger.info('开始')
    try:
        logger.info('手机号:%s, 内容: %s' % (mobiles, content))
        r = requests.post(phone_server, data=json.dumps(data), headers=header)
        logger.info('返回结果{}'.format(r))
    except Exception, e:
        logger.info(e)


def check_user():
    whoami = subprocess.check_output("whoami", shell=True).strip()
    if whoami.strip() != "root" and whoami.strip() != "zabbix":
        logger.info("only root and zabbix user can do this!")
        sys.exit(5)
    else:
        logger.info(whoami)

def check_logfile():
    ret = os.path.exists("/usr/local/zabbix/bin/phonelogs/phone-"+day+".log")
    if not ret:
        subprocess.call("touch /usr/local/zabbix/bin/phonelogs/phone-"+day+".log", shell=True)
        subprocess.call("chown zabbix:zabbix /usr/local/zabbix/bin/phonelogs/phone-"+day+".log", shell=True)

def pickup_data(message):
    ct = message.split("\n")
    logger.info('解析message：{}'.format(ct))
    for i in ct:
        logger.info('message字段解析为：{}'.format(i))
        if i.strip().startswith("告警主机"):
            hostname = i.split("：")[1].replace("\r", "")
            logger.info(u'告警主机/hostname: {0}'.format(hostname))
            return hostname
if __name__ == "__main__":
    check_user()
    check_logfile()
    send_phone()
